import 'package:json_annotation/json_annotation.dart';

/**
 * 笔记数据模型
 * 包含笔记的基本信息和内容
 */
@JsonSerializable()
class Note {
  final int id;
  final String title;
  final String content;
  final int folderId;
  final DateTime createdAt;
  final DateTime updatedAt;
  final List<String> tags;
  final String? syncStatus; // 同步状态：pending, synced, error

  const Note({
    required this.id,
    required this.title,
    required this.content,
    required this.folderId,
    required this.createdAt,
    required this.updatedAt,
    this.tags = const [],
    this.syncStatus,
  });

  /**
   * 从 JSON 创建 Note 对象
   */
  factory Note.fromJson(Map<String, dynamic> json) {
    return Note(
      id: json['id'] as int,
      title: json['title'] as String,
      content: json['content'] as String,
      folderId: json['folderId'] as int,
      createdAt: DateTime.parse(json['createdAt'] as String),
      updatedAt: DateTime.parse(json['updatedAt'] as String),
    );
  }

  /**
   * 将 Note 对象转换为 JSON
   */
  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'title': title,
      'content': content,
      'folderId': folderId,
      'createdAt': createdAt.toIso8601String(),
      'updatedAt': updatedAt.toIso8601String(),
    };
  }

  /**
   * 创建 Note 的副本，可选择性地更新某些字段
   */
  Note copyWith({
    int? id,
    String? title,
    String? content,
    int? folderId,
    DateTime? createdAt,
    DateTime? updatedAt,
    List<String>? tags,
    String? syncStatus,
  }) {
    return Note(
      id: id ?? this.id,
      title: title ?? this.title,
      content: content ?? this.content,
      folderId: folderId ?? this.folderId,
      createdAt: createdAt ?? this.createdAt,
      updatedAt: updatedAt ?? this.updatedAt,
      tags: tags ?? this.tags,
      syncStatus: syncStatus ?? this.syncStatus,
    );
  }

  /**
   * 获取笔记内容的预览文本（去除 Markdown 格式）
   */
  String get preview {
    String text = content
        .replaceAll(RegExp(r'#+ '), '') // 移除标题标记
        .replaceAll(RegExp(r'\*\*(.*?)\*\*'), r'$1') // 移除粗体标记
        .replaceAll(RegExp(r'\*(.*?)\*'), r'$1') // 移除斜体标记
        .replaceAll(RegExp(r'`(.*?)`'), r'$1') // 移除代码标记
        .replaceAll(RegExp(r'\n+'), ' ') // 将换行符替换为空格
        .trim();
    
    return text.length > 100 ? '${text.substring(0, 100)}...' : text;
  }

  /**
   * 获取笔记字数
   */
  int get wordCount => content.length;

  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
      other is Note &&
          runtimeType == other.runtimeType &&
          id == other.id;

  @override
  int get hashCode => id.hashCode;

  @override
  String toString() {
    return 'Note{id: $id, title: $title, folderId: $folderId}';
  }
}